package com.fastloan.mgt.customer.web;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fastloan.common.model.CheckResult;
import com.fastloan.mgt.customer.model.*;
import com.fastloan.mgt.customer.model.vo.CustomerAppExt;
import com.fastloan.mgt.customer.model.vo.CustomerExt;
import com.fastloan.mgt.customer.model.vo.StockCustomer;
import com.fastloan.mgt.customer.service.*;
import com.fastloan.safe.core.param.RoleTypeEnum;
import com.fastloan.safe.core.util.ManagerKit;
import com.fastloan.utils.ObjUtil;
import com.kawins.base.baseabs.BaseController;
import com.kawins.result.ResultEnum;
import com.kawins.result.ResultTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by gelon on 2017/11/6.
 */
@RestController
@RequestMapping("/api/zy/web/customer")
public class WebCustomerController extends BaseController<ZyCustomer> {

    @Autowired
    ZyCustomerService customerService;

    @Autowired
    ZyCustomerOtherBankService otherBankService;

    @Autowired
    ZyCustomerFinancingService financingService;

    @Autowired
    private ZyCustomerCardService customerVerifyService;

    @Autowired
    private CustomerAmountService customerAmountService;

    @Autowired
    private CustomerCreditService customerCreditService;


    /**
     * 获取客户信息
     */
    @PostMapping("/customers")
    public ResultTo customers(String cname, String storeName, Integer customerStatus) {
        Map<String, Object> map = new HashMap<>();
        if (ManagerKit.getRole().getIndexType().equals(RoleTypeEnum.MANAGER.getCode())) {
            map.put("userId", ManagerKit.getUserId());
        } else if (ManagerKit.getRole().getIndexType().equals(RoleTypeEnum.ORG_ADMIN.getCode())) {
            map.put("orgId", ManagerKit.getOrgId());
        }
        map.put("customerStatus", customerStatus);
        if (!ObjUtil.isEmpty(cname)) {
            map.put("cname", cname);
        }
        if (!ObjUtil.isEmpty(storeName)) {
            map.put("storeName", storeName);
        }
        return dataPage(customerService, CustomerExt.class, "queryCustomerExt", map);
    }


    /**
     * 新增一个营销客户
     */
    @PostMapping("/addCustomer")
    public ResultTo addCustomer(ZyCustomerStore zyCustomerStore, ZyCustomer zyCustomer,
                                MultipartFile file) {
        zyCustomer.setPhoneNum(zyCustomerStore.getOwnerPhoneNum());
        if (zyCustomer.getPhoneNum() == null) {
            return new ResultTo(ResultEnum.OPERATION_FAILED);
        }
        customerService.addByStore(zyCustomerStore, zyCustomer, file);
        return new ResultTo();
    }


    /**
     * 获取单个营销客户的营销维护信息
     */
    @GetMapping("/customerMarketingInfo/{customerId}")
    public ResultTo getCustomerMarketingInfo(@PathVariable("customerId") String customerId) {
        Map<String, Object> map = customerService.getCustomerInfo(customerId);
        if (map != null) {
            return new ResultTo().setData(map);
        }
        return new ResultTo(ResultEnum.PARAM_ERROR);
    }


    /**
     * 统计客户经理营销信息
     */
    @GetMapping("/getMarketing/{dateType}")
    //@Todo 暂时不做
    public ResultTo getMarketing(@PathVariable("dateType") Integer dateType) {
//        customerService.queryCountMarketing(map);
        return null;
    }

    /**
     * 获取客户营销历史
     */
    @GetMapping("/customerMarketing/{customerId}")
    public ResultTo customerMarketing(@PathVariable("customerId") String customerId) {
        Map<String, Object> map = new HashMap<>();
        map.put("customerId", customerId);
        return dataPage(customerService, ZyCustomerMarketion.class, "queryCustomerMartion", map);
    }

    /**
     * 更新一次营销信息
     *
     * @param customerJson           客户json
     * @param customerBusinessJson   客户商业信息
     * @param customerFinancingJson  客户融资信息
     * @param customerLoanDemandJson 客户贷款需求信息
     * @param customerMarketionJson  客户营销信息
     * @param customerMyBankJson     客户与我行信息
     * @param customerOtherBankJson  客户与他行信息
     * @param customerStoreJson      客户店铺信息
     * @param file                   店铺招牌
     */
    @PostMapping("/customerMarketion/save")
    public ResultTo updateCustomerMarketion(String customerJson, String customerBusinessJson,
                                            String customerFinancingJson, String customerLoanDemandJson,
                                            String customerMarketionJson, String customerMyBankJson, String customerOtherBankJson,
                                            String customerStoreJson, MultipartFile file) {

        ZyCustomer customer = JSONObject.parseObject(customerJson, ZyCustomer.class);
        ZyCustomerBusiness customerBusiness = JSONObject.parseObject(customerBusinessJson, ZyCustomerBusiness.class);
        List<ZyCustomerFinancing> customerFinancings = JSONArray.parseArray(customerFinancingJson, ZyCustomerFinancing.class);
        ZyCustomerLoanDemand customerLoanDemand = JSONObject.parseObject(customerLoanDemandJson, ZyCustomerLoanDemand.class);
        ZyCustomerMarketion customerMarketion = JSONObject.parseObject(customerMarketionJson, ZyCustomerMarketion.class);
        ZyCustomerMyBank customerMyBank = JSONObject.parseObject(customerMyBankJson, ZyCustomerMyBank.class);
        List<ZyCustomerOtherBank> customerOtherBanks = JSONArray.parseArray(customerOtherBankJson, ZyCustomerOtherBank.class);
        ZyCustomerStore customerStore = JSONObject.parseObject(customerStoreJson, ZyCustomerStore.class);

        customerService.updates(customer, customerBusiness, customerFinancings, customerLoanDemand, customerMarketion, customerMyBank,
                customerOtherBanks, customerStore, file);
        return new ResultTo();
    }


    /**
     * 删除一条他行记录
     */
    @DeleteMapping("/otherBank")
    public ResultTo deleteOtherBank(String otherBankId) {
        if (otherBankService.deleteByPrimaryKey(otherBankId) == 1) {
            return new ResultTo();
        }
        return new ResultTo(ResultEnum.OPERATION_FAILED);
    }

    /**
     * 删除一条融资记录
     */
    @DeleteMapping("/fiancing")
    public ResultTo deleteFiancing(String fiancingId) {
        if (financingService.deleteByPrimaryKey(fiancingId) == 1) {
            return new ResultTo();
        }
        return new ResultTo(ResultEnum.OPERATION_FAILED);
    }


    /**
     * 存量客户信息
     */
    @PostMapping("/stockCustomers")
    public ResultTo stockCustomers(String cname, String cardNum) {
        Map<String, Object> map = new HashMap<>();
        map.put("userId", ManagerKit.getUserId());
        map.put("cname", cname);
        map.put("cardNum", cardNum);
        return dataPage(customerService, StockCustomer.class, "queryStockCustomers", map);
    }

    /**
     * 客户进件历史
     */
    @PostMapping("/customerApps")
    public ResultTo customerApps(String appId, String produceName, String customerName) {
        Map<String, Object> map = new HashMap<>();
        map.put("appId", appId);
        map.put("producename", produceName);
        map.put("customerName", customerName);
        map.put("userId", ManagerKit.getUserId());
        return dataPage(customerService, CustomerAppExt.class, "queryApp", map);
    }

    /**
     * 绑定银行卡
     *
     * @param cardNum 卡号
     * @return 结果
     */
    @PostMapping("/bindCard/{cardNum}/{phone}")
    public ResultTo bindCard(@PathVariable("cardNum") String cardNum, @PathVariable("phone") String phone) {
        return customerVerifyService.bindCard(cardNum, phone, ManagerKit.getCustomerId());
    }

    /**
     * 解绑银行卡
     *
     * @param cardNum 卡号
     * @return 结果
     */
    @DeleteMapping("/unbindCard/{cardNum}")
    public ResultTo unbindCard(@PathVariable("cardNum") String cardNum) {
        int result = customerVerifyService
                .delete(new ZyCustomerCard(ManagerKit.getCustomerId(), cardNum));
        return result == 1 ? new ResultTo() : new ResultTo(ResultEnum.OPERATION_FAILED);
    }

    /**
     * 获得客户银行卡
     *
     * @return 结果
     */
    @GetMapping("/bankCard")
    public ResultTo bankCard() {
        return new ResultTo().setData(customerVerifyService.getCustomerCard(ManagerKit.getCustomerId()));
    }

    @PostMapping("/bugStart/{customerId}")
    public ResultTo reset(@PathVariable String customerId) {
        ZyCustomer zyCustomer = customerService.selectByPrimaryKey(customerId);
        zyCustomer.setVerify(null);
        customerService.updateByPrimaryKey(zyCustomer);
        return new ResultTo();
    }

    /**
     * 预授信检查
     *
     * @param customerId
     * @param productId
     * @param applyAmount
     * @return
     */
    @PostMapping("/creditVerify")
    public ResultTo creditVerify(String customerId, String productId, BigDecimal applyAmount) {
        try {
            CheckResult checkResult = customerAmountService.creditVerify(customerId, productId);
            if (!checkResult.isCheckResult()) {
                return new ResultTo(ResultEnum.OPERATION_FAILED, checkResult.getCheckMsg());
            }
            return new ResultTo().setData(checkResult.getData());
        } catch (Exception e) {
            e.printStackTrace();
            return new ResultTo(ResultEnum.OPERATION_FAILED, "无需重复申请");
        }
    }

    /**
     * 人行征信
     *
     * @param customerCredit
     * @return
     */
    @PostMapping("/bankReference")
    public ResultTo bankReference(CustomerCredit customerCredit) {
        customerCredit.setCustomerId(ManagerKit.getCustomerId());
        CustomerCredit customerCredit1 = customerCreditService.selectByPrimaryKey(customerCredit.getCustomerId());
        if (customerCredit1 == null) {
            customerCreditService.insert(customerCredit);
        } else {
            customerCreditService.updateByPrimaryKeySelective(customerCredit);
        }
        return new ResultTo();
    }

}
